<?php

namespace app\api\controller;

use app\models\{User as Users, Region, Second, MenuSecond, Favorites, LeaveMessage, Likes, Admin, Circle as Circles, Config, Riderlist, RiderStreet, Carlist, Carorder};
use think\Facade\Config as Configs;
use app\facade\Mns;
use think\Validate;
use think\Db;

class Circle extends Base
{

    public function corder_true()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require',
                'status' => 'require|in:2,5',
            ], [
                'id.require' => 'ID不能为空',
                'status.require' => '状态类型不能为空',
                'status.in' => '状态类型不正确',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $order = (new Carorder())->where(['user_id' => $this->request->user_id, 'id' => $data['id']])->find();
            if (empty($order)) {
                $this->result([], 1, '订单不存在');
            }
            switch ($data['status']) {
                case '2':
                    $this->result([], 1, '暂未开放');
                    break;
                case '5':
                    //获到付款直接取消
                    if ($order['status'] != 1 && $order['status'] != 2 && $order['status'] != 3) {
                        $this->result([], 1, '订单状态不可取消');
                    }
                    if ($order['ispay'] == 1) {
                        $res = (new Carorder())->where(['id' => $data['id']])->update(['status' => 5]);
                        if ($res) {
                            $this->result([], 0, '操作成功');
                        }
                        $this->result([], 1, '操作失败，请重试');
                    }
                    break;
                default:
                    $this->result([], 1, '状态类型不正确');
                    break;
            }
            $this->result([], 1, '下单成功，请重试');
        }
    }

    public function cdetail()
    {
        $id = $this->request->get('id/d', 0);
        $lists = (new Carorder())->field('id,type,ordersn,appoint,address,fee,status,ispay,ishave,bighand,sfloor,efloor,mobile,listname,km,lc,total,remark')->where('user_id', $this->request->user_id)->where('id', $id)->find();
        if ($lists) {
            $lists['address'] = json_decode($lists['address'], true);
            $lists['fee'] = json_decode($lists['fee'], true);
            $lists['status_text'] = $lists->status_text;
        }
        $this->result($lists, 0, '获取成功');
    }

    public function corder()
    {
        $status = $this->request->get('status/d', 0);
        $lists = (new Carorder())->where('user_id', $this->request->user_id)
            ->order('id desc')->field('id,listname,appoint,address,total,type,status,orders_id');
        switch ($status) {
            case '1':
                $lists = $lists->where('status', 1);
                break;
            case '2':
                $lists = $lists->where(['status' => [2, 3]]);
                break;
            case '3':
                $lists = $lists->where('status', 4);
                break;
            case '4':
                $lists = $lists->where('status', 5);
                break;
            default:
                # code...
                break;
        }
        $lists = $lists->paginate(20, false, ['query' => $this->request->param()]);
        foreach ($lists as $list) {
            $list['address'] = json_decode($list['address'], true);
            $list['status_text'] = $list->status_text;
            $list['cmobile'] = '';
        }
        $this->result($lists, 0, '获取成功');
    }

    public function carlist()
    {
        if ($this->request->isPost()) {
            $id = $this->request->post('id/d', 0);
            $lists = (new Carlist())->where('id', $id)->find();
            if ($lists) {
                $lists['images'] = json_decode($lists['images'], true);
                $lists['params'] = json_decode($lists['params'], true);
            }
            $this->result($lists, 0, '获取成功');
        } else {
            $data = $this->request->get();
            $street = $data['street'] ?? 0;
            $area = (new Region())->where(['id' => $street, 'level' => 4])->value('area_code') ?? 0;
            $where = [
                'street' => $street
            ];
            $where1 = [
                'street' => $street,
                'area' => $area,
            ];

            if (!empty($data['type']) && $data['type'] == 2) {
                $where['type'] = 2;
                $where1['type'] = 2;
                $where2['type'] = 2;
            }
            $lists = (new Carlist())
                ->whereOr(function ($query) use ($where) {
                    $query->where($where);
                })->whereOr(function ($query) use ($where1) {
                    $query->where($where1);
                })->field('province,city,area,street,created', true)->select();
            foreach ($lists as $list) {
                $list['images'] = json_decode($list['images'], true);
                $list['params'] = json_decode($list['params'], true);
            }
            $this->result($lists, 0, '获取成功');
        }
    }

    public function cputorder()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require',
                'type' => 'require|in:1,2',
                'appoint' => 'require',
                'address' => 'require',
                'ishave' => 'require|in:1,2',
                'bighand' => 'require',
                'sfloor' => 'require',
                'efloor' => 'require',
                'mobile' => 'require',
                'fllorcar' => 'require',
                'remark' => 'require',
                'istype' => 'require|in:1,2'
            ], [
                'id.require' => '车类型不能为空',
                'type.require' => '拉货类型不能为空',
                'type.in' => '拉货类型不正确',
                'appoint.require' => '预约时间不能为空',
                'address.require' => '地址信息不能为空',
                'ishave.require' => '搬运类型不能为空',
                'ishave.in' => '搬运类型不正确',
                'bighand.require' => '大物件不能为空',
                'sfloor.require' => '出发楼层不能为空',
                'efloor.require' => '卸货楼层不能为空',
                'mobile.require' => '联系电话不能为空',
                'fllorcar.require' => '跟车人不能为空',
                'remark.require' => '备注不能为空',
                'istype.require' => '访问类型不能为空',
                'istype.in' => '访问类型不正确',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $address = json_decode($data['address'], true) ?? [];
            if (count($address) < 2) {
                $this->result([], 1, '装货与卸货地址均必须填写');
            }
            $lists = (new Carlist())->where('id', $data['id'])->find();
            if (empty($lists)) {
                $this->result([], 1, '车辆参数缺失');
            }
            //费率明细返回
            $fee = [
                'trafee' => (float)$lists['start'] ?? 0, //基础路费
                'fjtrafee' => 0, //附加路费
                'tracfee' => 0, //基础搬运费
                'bigtracfee' => 0, //基础大物件搬运费
                'lcfee' => 0, //楼层费
                'biglcfee' => 0, //大件楼层费
            ];
            $lc = 0; //楼层统计
            $km = 0; //距离统计
            if ($data['ishave'] == 2) {
                $fee['tracfee'] = (float)$lists['handling'] ?? 0;
                //判断有没有大物件
                if ($data['bighand'] > 0) {
                    $fee['bigtracfee'] = (float)$lists['bighandling'] ?? 0;
                }
                //楼层费用
                if ($data['sfloor'] > 1) {
                    if ($data['sfloor'] == 10000) {
                        $lc += 1;
                    } else {
                        $lc += $data['sfloor'];
                    }
                }
                if ($data['efloor'] > 1) {
                    if ($data['efloor'] == 10000) {
                        $lc += 1;
                    } else {
                        $lc += $data['efloor'];
                    }
                }
                $fee['lcfee'] = ($lists['lcfee'] ?? 0) * $lc;
                $fee['biglcfee'] = ($lists['floorfee'] ?? 0) * $lc * $data['bighand'];
            }
            foreach ($address as $k => $add) {
                if (empty($add['name']) || empty($add['mobile']) || empty($add['lat']) || empty($add['lon']) || empty($add['street']) || empty($add['getaddress']) || empty($add['address'])) {
                    $this->result([], 1, '地址参数缺失');
                }
                //判断是否下单区域
                if ($k == 0) {
                    $area = (new Region())->where(['id' => $add['street'], 'level' => 4])->value('area_code') ?? 0;
                    if ($lists['street'] > 0 && $add['street'] != $lists['street']) {
                        $this->result([], 1, '服务商不在装货街道访问,请定位装货街道后重新下单');
                    }
                    if ($lists['street'] == 0 && $area != $lists['area']) {
                        $this->result([], 1, '服务商不在装货街道访问,请定位装货街道后重新下单');
                    }
                    $data['street'] = $add['street'];
                    //计算楼层
                } else {
                    $km += getDistance($add['lon'], $add['lat'], $address[$k - 1]['lon'], $address[$k - 1]['lat'], 2, 2);
                }
            }
            $km = floor($km);
            //额外路费      
            switch ($km) {
                case $km > 100:
                    $fee['fjtrafee'] += floor(20 * $lists['every1'] * 100) / 100;
                    $fee['fjtrafee'] += floor(25 * $lists['every2'] * 100) / 100;
                    $fee['fjtrafee'] += floor(50 * $lists['every3'] * 100) / 100;
                    $fee['fjtrafee'] += floor(($km - 100) * $lists['every'] * 100) / 100;
                    break;
                case $km > 50:
                    $fee['fjtrafee'] += floor(20 * $lists['every1'] * 100) / 100;
                    $fee['fjtrafee'] += floor(25 * $lists['every2'] * 100) / 100;
                    $fee['fjtrafee'] += floor(($km - 50) * $lists['every3'] * 100) / 100;
                    break;
                case $km > 25:
                    $fee['fjtrafee'] += floor(20 * $lists['every1'] * 100) / 100;
                    $fee['fjtrafee'] += floor(($km - 25) * $lists['every2'] * 100) / 100;
                    break;
                case $km > 5:
                    $fee['fjtrafee'] += floor(($km - 5) * $lists['every1'] * 100) / 100;
                    break;
                default:
                    # code...
                    break;
            }
            if ($data['istype'] == 1) {
                $this->result($fee, 0, '获取价格');
            } else {
                $total = $fee['trafee'] + $fee['fjtrafee'] + $fee['tracfee'] + $fee['bigtracfee'] + $fee['lcfee'] + $fee['biglcfee'];
                $data['ordersn'] = time() . rand(11111, 99999);
                $data['listid'] = $data['id'];
                $data['listname'] = $lists['title'];
                $data['km'] = $km;
                $data['lc'] = $lc;
                $data['fee'] = json_encode($fee, true);
                $data['total'] = $total;
                $data['ispay'] = $data['ispay'] ?? 1;
                if ($data['ispay'] == 1) {
                    $data['status'] = 2;
                    $data['paytime'] = date('Y-m-d H:i:s');
                } else {
                    $this->result([], 1, '暂不支持支付类型');
                }
                $data['user_id'] = $this->request->user_id;
                unset($data['id']);
                $res = (new Carorder())->allowfield(true)->save($data);
                if ($res) {
                    $this->result([], 0, '下单成功');
                }
                $this->result([], 1, '下单失败，请重试');
            }
        }
    }

    public function mycircle()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'title' => 'require',
                'descs' => 'require',
                'images' => 'require',
                'type' => 'require',
                'price' => 'require',
                'oprice' => 'require',
                'phone' => 'require',
                'lon' => 'require',
                'lat' => 'require',
                'posaddress' => 'require',
            ], [
                'title.require' => '信息标题不能为空',
                'descs.require' => '信息描述不能为空',
                'images.require' => '图片描述不能为空',
                'type.require' => '分类信息不能为空',
                'price.require' => '售卖价格不能为空',
                'oprice.require' => '原购买价格不能为空',
                'phone.require' => '联系电话不能为空',
                'lon.require' => '坐标不能为空',
                'lat.require' => '坐标不能为空',
                'posaddress.require' => '详细地址不能为空'
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $rider = (new Riderlist())->where(['user_id' => $this->request->user_id])->find();
            if (empty($rider)) {
                $this->result([], 1, '非发布人员不可发布');
            }
            $riderstreet = (new RiderStreet())->where(['riderid' => $rider['id'], 'status' => 2])->find();
            if (empty($riderstreet)) {
                $this->result([], 1, '非发布人员不可发布');
            }
            $config = config('wechat.');
            $app = Factory::miniProgram($config);
            $accessToken = $app->access_token;
            //判断分类是否存在
            $menu = (new MenuSecond())->where('id', $data['type'])->find();
            if (empty($menu)) {
                $this->result([], 1, '分类不存在');
            }
            $url = 'https://apis.map.qq.com/ws/geocoder/v1';
            $url = $url . "?location=" . $data['lat'] . ',' . $data['lon'] . '&key=2AEBZ-YK23W-XISR6-ROOGV-VOLI7-46FFT&poi_options=radius=50;policy=5';
            try {
                $result = getData($url);
            } catch (\Exception $e) {
                $this->result([], 1, $e->getMessage());
            }
            if (!empty($result) && $result['status'] == 0) {
                if (empty($result['result']['ad_info']['adcode'])) {
                    $this->result([], 1, '定位解析失败，请重试');
                }
                $data['street'] = (new Region())
                    ->where(['level' => 4])
                    ->where('area_code', 'like', '%' . $result['result']['ad_info']['adcode'] . '%')
                    ->where('name|remark', 'like', '%' . $result['result']['address_reference']['town']['title'] . '%')->value('id') ?? 0;
            }
            $street = (new Region())->where(['id' => $data['street'], 'level' => 4])->find();
            $area = (new Region())->where(['id' => $street['parent_id'] ?? 0, 'level' => 3])->find();
            $data['area'] = $area['area_code'] ?? 0;
            $city = (new Region())->where(['id' => $area['parent_id'] ?? 0, 'level' => 2])->find();
            $data['city'] = $city['area_code'] ?? 0;
            $province = (new Region())->where(['id' => $city['parent_id'] ?? 0, 'level' => 1])->find();
            $data['province'] = $province['area_code'] ?? 0;
            $data['user_id'] = $this->request->user_id;
            if (!empty($data['id'])) {
                $Second = (new Second())->where(['id' => $data['id'], 'user_id' => $data['user_id']])->find();
                if (empty($Second)) {
                    $this->result([], 1, '信息不存在');
                }
                if ($Second['status'] == 3) {
                    $data['status'] = 1;
                }
                $res = (new Second())->allowfield(true)->save($data, ['id' => $data['id']]);
            } else {
                $data['status'] = 1;
                $res = (new Second())->allowfield(true)->save($data);
            }
            if ($res) {
                $this->result([], 0, '操作成功');
            }
            $this->result([], 1, '操作失败，请重试');
        } else {
            $list = (new Second())->order('id desc')->field('status,isshow,images,id,price,oprice,title')->where('isdel', 1)->where('user_id', $this->request->user_id)->paginate(20, false, ['query' => $this->request->param()])->each(function ($item) {
                $item['images'] = json_decode($item['images'], true);
                return $item;
            });
            $this->result($list, 0, '获取成功');
        }
    }

    public function Second_del()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'id' => 'require',
        ], [
            'id.require' => 'ID不能为空',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $result = (new Second())->where(['id' => $data['id'], 'user_id' => $this->request->user_id])->find();
        if (empty($result)) {
            $this->result([], 1, '信息不存在');
        }
        if (!empty($data['isdel']) && $result['isdel'] == 1) {
            $res = (new Second())->where('id', $result['id'])->update(['isdel' => 2]);
            if ($res) {
                $this->result([], 0, '操作成功');
            }
        }
        if (!empty($data['isshow'])) {
            $isshow = 1;
            if ($result['isshow'] == 1) {
                $isshow = 2;
            }
            $res = (new Second())->where('id', $result['id'])->update(['isshow' => $isshow]);
            if ($res) {
                $this->result([], 0, '操作成功');
            }
        }
        $this->result([], 1, '操作失败');
    }

    public function Second_list()
    {
        $data = $this->request->get();
        if (empty($data['lon']) || empty($data['lat'])) {
            $this->result([], 1, '请上传坐标信息');
        }
        if (empty($data['type'])) {
            $this->result([], 1, '请上传数据类型');
        }
        $filed = 'ROUND(6378.138*2*ASIN(SQRT(POW(SIN((' . $data['lat'] . '*PI()/180-lat*PI()/180)/2),2)+COS(' . $data['lat'] . '*PI()/180)*COS(lat*PI()/180)*POW(SIN((' . $data['lon'] . '*PI()/180-lon*PI()/180)/2),2)))*1000) AS distance';
        $list = (new Second())->where('status', 2)->where('isdel', 1)->field('id,user_id,ishot,title,lat,lon,images,price,oprice,created,' . $filed);
        switch ($data['type']) {
            case '1':
                if (!empty($data['order'])) {
                    if ($data['order'] == 2) {
                        $list = $list->order('price asc');
                    } else if ($data['order'] == 3) {
                        $list = $list->order('price desc');
                    } else {
                        $list = $list->order('id desc');
                    }
                } else {
                    $list = $list->order('id desc');
                }
                $menuid = $data['menuid'] ?? 0;
                if (!empty($menuid)) {
                    $list = $list->where('type', $menuid);
                }
                break;
            case '2':
                if (!empty($data['order'])) {
                    if ($data['order'] == 2) {
                        $list = $list->order('price asc');
                    } else if ($data['order'] == 3) {
                        $list = $list->order('price desc');
                    } else {
                        $list = $list->order('distance asc');
                    }
                } else {
                    $list = $list->order('distance asc');
                }
                $menuid = $data['menuid'] ?? 0;
                if (!empty($menuid)) {
                    $list = $list->where('type', $menuid);
                }
                break;
            case '3':
                $menuid = $data['menuid'] ?? 0;
                if (empty($menuid)) {
                    $this->result([], 1, '请上传分类ID');
                }
                if (!empty($data['order'])) {
                    if ($data['order'] == 2) {
                        $list = $list->where('type', $menuid)->order('price asc');
                    } else if ($data['order'] == 3) {
                        $list = $list->where('type', $menuid)->order('price desc');
                    } else {
                        $list = $list->where('type', $menuid)->order('id desc');
                    }
                } else {
                    $list = $list->where('type', $menuid)->order('id desc');
                }
                break;
            case '4':
                if (!empty($data['order'])) {
                    if ($data['order'] == 2) {
                        $list = $list->order(['ishot' => 'desc'])->order('price asc');
                    } else if ($data['order'] == 3) {
                        $list = $list->order(['ishot' => 'desc'])->order('price desc');
                    } else {
                        $list = $list->order(['ishot' => 'desc'])->order('id desc');
                    }
                } else {
                    $list = $list->order(['ishot' => 'desc'])->order('id desc');
                }
                $menuid = $data['menuid'] ?? 0;
                if (!empty($menuid)) {
                    $list = $list->where('type', $menuid);
                }
                break;
            default:
                break;
        }
        if (!empty($data['price'])) {
            $list = $list->where('price', '>=', $data['price']);
        }
        if (!empty($data['maxprice'])) {
            $list = $list->where('price', '<', $data['maxprice']);
        }
        if (!empty($data['title'])) {
            $list = $list->where('title', 'like', '%' . $data['title'] . '%');
        }

        $list = $list->paginate(20, false, ['query' => $this->request->param()])->each(function ($item) {
            $item['distance'] = round($item['distance'] / 1000, 4);
            $item['images'] = json_decode($item['images'], true);
            $user = (new Users())->where('id', $item['user_id'])->find();
            $item['nickname'] = $user['nickname'] ?? '';
            $item['logo'] = $user['logo'] ?? '';
            return $item;
        });
        $this->result($list, 0, '获取成功');
    }

    public function Second_type()
    {
        $list = (new MenuSecond())->where('ishsow', 1)->order('sort desc')->field('id,name,images,ishot')->select();
        $this->result($list, 0, '获取成功');
    }

    public function Second_detail()
    {
        $id = $this->request->get('id/d', 0);
        $result = (new Second())->where('id', $id)->where('isdel', 1)->find();
        if ($result) {
            $result['images'] = json_decode($result['images'], true);
            $user = (new Users())->where('id', $result['user_id'])->find();
            $result['type_name'] = (new MenuSecond())->where('id', $result['type'])->value('name');
            $result['nickname'] = $user['nickname'] ?? '';
            $result['logo'] = $user['logo'] ?? '';
            $result['favorites'] = (new Favorites())->where(['user_id' => $this->request->user_id, 'type' => 1, 'getid' => $result['id']])->count();
        }
        $this->result($result, 0, '获取成功');
    }

    public function  favorites()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'type' => 'require',
                'getid' => 'require'
            ], [
                'type.require' => '类型不能为空',
                'getid.require' => '信息ID不能为空'
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            //查询信息是否存在
            $result = (new Favorites())->where(['user_id' => $this->request->user_id, 'type' => $data['type'], 'getid' => $data['getid']])->find();
            if ($result) {
                $res = (new Favorites())->where(['id' => $result['id']])->delete();
                if ($res) {
                    $this->result([], 0, '已取消收藏');
                }
                $this->result([], 0, '取消收藏失败，请重试');
            } else {
                $res = (new Favorites())->save([
                    'user_id' => $this->request->user_id,
                    'type' => $data['type'],
                    'getid' => $data['getid']
                ]);
                if ($res) {
                    $this->result([], 0, '已收藏');
                }
                $this->result([], 0, '收藏失败，请重试');
            }
        } else {
            $data = $this->request->get();
            $validate = new Validate([
                'type' => 'require'
            ], [
                'type.require' => '类型不能为空'
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $result = (new Favorites())->where(['user_id' => $this->request->user_id])->select();
            foreach ($result as $results) {
                if ($results['type'] == 1) {
                    $results['detail'] =  (new Second())->where('id', $results['getid'])->find();
                    $results['detail']['images'] = json_decode($results['detail']['images'], true);
                    $user = (new Users())->where('id', $results['user_id'])->find();
                    $results['detail']['nickname'] = $user['nickname'] ?? '';
                    $results['detail']['logo'] = $user['logo'] ?? '';
                }
            }
            $this->result($result, 0, '获取成功');
        }
    }


    public function  leave_message()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'message' => 'require',
                'type' => 'require',
                'getid' => 'require'
            ], [
                'message.require' => '信息不能为空',
                'type.require' => '类型不能为空',
                'getid.require' => '信息ID不能为空'
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            //查询信息是否存在
            $data['user_id'] = $this->request->user_id;
            $data['top_str'] = '';
            if (!empty($data['topid'])) {
                $topmessage = (new LeaveMessage())->where('id', $data['topid'])->find();
                if (empty($topmessage)) {
                    $this->result([], 1, '回复的信息已被删除，请重新评论');
                }
                $data['heattop'] = $data['topid'];
                if (!empty($topmessage['heattop'])) {
                    $data['heattop'] = $topmessage['heattop'];
                }
                $data['touser_id'] = $topmessage['user_id'];
                $data['top_str'] = $topmessage['top_str'] . ',' . $topmessage['id'];
                if (empty($topmessage['top_str'])) {
                    $data['top_str'] = $topmessage['id'];
                }
            }
            $top_str = array_filter(explode(',', $data['top_str']));
            Db::startTrans();
            try {
                (new LeaveMessage())->allowfield(true)->save($data);
                if ($top_str) {
                    (new LeaveMessage())->where(['id' => $top_str])->setInc('heat');
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result([], 1, '评论失败，请重试');
            }
            $this->result([], 0, '评论成功');
        } else {
            $data = $this->request->get();
            $validate = new Validate([
                'type' => 'require',
                'getid' => 'require'
            ], [
                'type.require' => '类型不能为空',
                'getid.require' => '信息ID不能为空'
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $result = (new LeaveMessage())
                ->order('heat desc')
                ->field('id,user_id,message,created')
                ->where(['type' => $data['type'], 'getid' => $data['getid'], 'topid' => 0])
                ->paginate(20, false, ['query' => $this->request->param()]);
            foreach ($result as $results) {
                $user = (new Users())->where('id', $results['user_id'])->find();
                $results['user_name'] = $user['nickname'] ?? '';
                $results['logo'] = $user['logo'] ?? '';
                $results['reply'] = (new LeaveMessage())
                    ->order('heat desc')
                    ->field('id,user_id,touser_id,message,created')
                    ->where(['type' => $data['type'], 'getid' => $data['getid'], 'heattop' => $results['id']])->limit(5)->select();
                foreach ($results['reply'] as $resultson) {
                    $userson = (new Users())->where('id', $resultson['user_id'])->find();
                    $resultson['user_name'] = $userson['nickname'] ?? '';
                    $resultson['user_logo'] = $userson['logo'] ?? '';
                    $touser_son = (new Users())->where('id', $resultson['touser_id'])->find();
                    $resultson['touser_name'] =  $touser_son['nickname'] ?? '';
                    $resultson['touser_logo'] =  $touser_son['logo'] ?? '';
                }
            }
            $this->result($result, 0, '获取成功');
        }
    }

    public function  likes()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'type' => 'require',
                'getid' => 'require'
            ], [
                'type.require' => '类型不能为空',
                'getid.require' => '信息ID不能为空'
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            //查询信息是否存在
            $result = (new Likes())->where(['user_id' => $this->request->user_id, 'type' => $data['type'], 'getid' => $data['getid']])->find();
            if ($result) {
                $res = (new Likes())->where(['id' => $result['id']])->delete();
                if ($res) {
                    $this->result([], 0, '已取消点赞');
                }
                $this->result([], 0, '取消点赞失败，请重试');
            } else {
                $res = (new Likes())->save([
                    'user_id' => $this->request->user_id,
                    'type' => $data['type'],
                    'getid' => $data['getid']
                ]);
                if ($res) {
                    $this->result([], 0, '已点赞');
                }
                $this->result([], 0, '点赞失败，请重试');
            }
        } else {
            $result = [
                'islike' => 0,
                'count' => 0,
                'list' => []
            ];
            $data = $this->request->get();
            $validate = new Validate([
                'type' => 'require',
                'getid' => 'require'
            ], [
                'type.require' => '类型不能为空',
                'getid.require' => '信息ID不能为空'
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $list = (new Likes())->where(['type' => $data['type'], 'getid' => $data['getid']])->select();
            foreach ($list as $k => $lists) {
                if ($lists['user_id'] == $this->request->user_id) {
                    $result['islike'] = 1;
                }
                $result['count'] += 1;
                if ($k < 10) {
                    $user_img = (new Users())->where('id', $lists['user_id'])->value('logo') ?? '';
                    $result['list'][] = $user_img;
                }
            }

            $this->result($result, 0, '获取成功');
        }
    }

    public function circle()
    {
        $name = (new Config())->where(['key_value' => 'name'])->value('value') ?? '';
        $logo = (new Config())->where(['key_value' => 'logo'])->value('value') ?? '';
        $result = (new Circles())->order(['ishot' => 'desc', 'id' => 'desc'])->field('ishot,updated,isshow,dates', true)->where('isshow', 1)->paginate(20, false, ['query' => $this->request->param()]);
        foreach ($result as $results) {
            $admin = (new Admin())->where('id', $results['adminid'])->find();
            $results['poster'] = $admin['poster'] ?? $name;
            $results['poster_logo'] = $admin['images'] ?? $logo;
            $results['replycount'] = 0;
            $results['favorites'] = (new Favorites())->where(['type' => 2, 'getid' => $results['id'], 'user_id' => $this->request->user_id])->count();
            $results['reply'] = [];
            $replylist = (new LeaveMessage())
                ->order(['heat' => 'desc', 'heattop' => 'asc'])
                ->field('id,user_id,message,created,touser_id')
                ->where(['type' => 2, 'getid' => $results['id']])->select();
            $replys2 = [];
            foreach ($replylist as $k =>  $replys) {
                $results['replycount'] += 1;
                if ($k < 5) {
                    $replys['user_name'] = (new Users())->where('id', $replys['user_id'])->value('nickname') ?? '';
                    if ($replys['touser_id']) {
                        $replys['touser_name'] = (new Users())->where('id', $replys['touser_id'])->value('nickname') ?? '';
                    }
                    $replys2[] = [
                        'id' => $replys['id'],
                        'user_name' => $replys['user_name'],
                        'touser_name' =>  $replys['touser_name'] ?? '',
                        'message' =>   $replys['message']
                    ];
                }
            }
            $results['reply'] = $replys2 ?? [];
        }
        $this->result($result, 0, '获取成功');
    }

    public function circle_detail()
    {
        $id = $this->request->get('id/d', 0);
        $result = (new Circles())->field('ishot,updated,isshow,dates', true)->where('isshow', 1)->find();
        if ($result) {
            $admin = (new Admin())->where('id', $result['adminid'])->find();
            $name = (new Config())->where(['key_value' => 'name'])->value('value') ?? '';
            $logo = (new Config())->where(['key_value' => 'logo'])->value('value') ?? '';
            $result['poster'] = $admin['poster'] ?? $name;
            $result['poster_logo'] = $admin['images'] ?? $logo;
        }
        $this->result($result, 0, '获取成功');
    }
}